#include "CodeScanner.h"


const std::regex CodeScanner::pattern("^<GET_ID_id=([0-9a-z]{32})&mac1=([0-9a-f:]{17})&mac2=([0-9a-f:]{17})&vc=(.{7})>$");//

//const std::regex CodeScanner::pattern("(?:\\[([0-9]{1,3})_([ABCabc])/([0-9]{1,3})/([0-9.]{1,7})\\])");



/**
* 新的UUID匹配
* <GET_ID_id=1a5ec6ebb2704e56b0db2a31bc92aedb&mac1=2e:b7:53:3f:47:9b&mac2=10:dc:db:b8:46:e7&vc=d74047d3>
* mac地址没有将点的位置计入匹配范围
*/
void CodeScanner::update(const int& command, void* data, const Task* pTask) noexcept { //std::string& id, std::string& mac1, std::string& mac2
    VersionInfo* pVersionInfo = reinterpret_cast<VersionInfo*> (data);

    VersionInfo& persistentVersionInfo = ConfigManagerSingleton::instance().getVersionInfo();

    persistentVersionInfo.uuidString = pVersionInfo->uuidString;
    persistentVersionInfo.mac1String = pVersionInfo->mac1String;
    persistentVersionInfo.mac2String = pVersionInfo->mac2String;

    ConfigManagerSingleton::instance().saveVersionInfo();

    delete pVersionInfo;

    releaseDynamicFunctor(pTask);
}


/**
 * 获取二维码数据
 * @return
 */
bool CodeScanner::recheck() noexcept {
    bool recheckResult = false;
    std::string result;
    try {
        mchannel.sendStringReturnString(std::string("<GET_ID>"), result);
        if ("<GET_ID_ERROR>" == result) {
            recheckResult = true;
        } else {
            std::smatch match;
            if ( std::regex_match(result, match, pattern)) {
                recheckResult = true;

                std::string id = match.str(1);
                std::string mac1 = match.str(2);
                std::string mac2 = match.str(3);

                VersionInfo* pVersionInfo = new VersionInfo;
                pVersionInfo->uuidString = id;
                pVersionInfo->mac1String = mac1;
                pVersionInfo->mac2String = mac2;

                Task* pTask = buildDynamicFunctor(&CodeScanner::update, this, 1, pVersionInfo);
                mpool->pushPool(pTask);

                LOG_INFO("new device id:%s,mac1:%s,mac2:%s", id.c_str(), mac1.c_str(), mac2.c_str());
            }
        }

        mdeviceStatisticInfo.setCheckStatus(recheckResult);
    } catch (std::exception& ex) {
        LOG_ERROR(ex.what());
    }
    return recheckResult;
}
